package com.hust360.percent.pojo;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.hust360.percent.PercentApplication;
import com.hust360.percent.pojo.User.UserDAO;

public class UserDAOImpl implements UserDAO {

	@Override
	public void save(User user) {
		ContentValues values = new ContentValues();
		values.put(User.ID, user.id);
		values.put(User.IMG, user.img);
		values.put(User.MAIL, user.mail);
		values.put(User.PASSWORD, user.password);
		values.put(User.USERNAME, user.username);
		synchronized (PercentApplication.localDB) {
			PercentApplication.localDB.insertWithOnConflict(User.TABLE, null,
					values, SQLiteDatabase.CONFLICT_REPLACE);
		}
	}

	@Override
	public User findByExample(User user) {
		User user2 = null;
		StringBuffer selection = new StringBuffer();
		if (user.id == null && user.mail == null && user.username == null) {
			return null;
		}

		if (user.password == null) {
			return null;
		} else {
			selection.append(User.PASSWORD + "='" + user.password + "' AND ");
		}

		if (user.id != null) {
			selection.append(User.ID + "='" + user.id + "' AND ");
		}

		if (user.img != null) {
			selection.append(User.IMG + "='" + user.img + "' AND ");
		}
		if (user.mail != null) {
			selection.append(User.MAIL + "='" + user.mail + "' AND ");
		}
		if (user.username != null) {
			selection.append(User.USERNAME + "='" + user.username + "' AND ");
		}
		selection.append(" '1'='1' ");
		Cursor c = PercentApplication.localDB.rawQuery(
				"SELECT * FROM user WHERE " + selection.toString(), null);
		if (c.getCount() == 1) {
			user2 = new UserLocal();
			user2.id = c.getLong(c.getColumnIndex(User.ID));
			user2.img = c.getString(c.getColumnIndex(User.IMG));
			user2.mail = c.getString(c.getColumnIndex(User.MAIL));
			user2.password = c.getString(c.getColumnIndex(User.PASSWORD));
			user2.username = c.getString(c.getColumnIndex(User.USERNAME));
		}
		return user2;
	}
}
